<?php
namespace Model;

use Think\Model;
use \Model\SkillModel;

class OrderModel extends CommonModel
{

    //用户B预约，提交订单
    public function model_submit_skill_order($data)
    {
        // echo "1";exit;
        $order = D('order');

        //实例化M()方法
        $Model = M();

        //开启事务
        $Model->startTrans();

        //处理数据（此处为测试数据，可改）

        // echo $data['order_skill_id'];exit;
		$skillmodel = new SkillModel;
        $skill = $skillmodel->where('skill_id='.$data['order_skill_id'])->find();
        $skill_state = $skill['skill_state'];
        if($skill_state!=1) {
            echo '{"msg":"商品已被预约！"}';return ;
        }
        // echo $skill_state;exit;
        // dump($skill_state);exit;


        $info1 = $order->add($data);
        $info2 = $skillmodel->model_set_skillstate_to_2($data['order_skill_id']);    //将商品的状态设置为2


        //根据返回值判断是否均执行成功
        if ($info1 && $info2) {
            //执行成功，提交事务
            $Model->commit();
            // $this->success('删除成功');
            echo '{"msg":"ok"}';return ;
        } else {
            //任一执行失败，执行回滚操作，相当于均不执行
            $Model->rollback();
            // $this->error('删除失败');
            echo '{"msg":"商品已被预约！"}';return;

        }

    }

    //根据b用户id获取等待的订单
    public function model_get_user_b_await_order($user_b_id) {
        $order = D('order');
        $sql = "SELECT order_id,order_skill_id,skill_title,skill_user,order_number,order_price,
        order_user_a_note,order_user_b_contact_way,order_user_a_default_contact_way_value,order_state,
        order_user_b_contact_way,order_user_b_contact_way_value,order_user_b_start_time,
        order_user_b_end_time,order_user_b_start_address,order_user_b_end_address
        FROM  wx_order left join wx_skill on wx_order.order_skill_id=wx_skill.skill_id
        WHERE wx_order.order_user_b_id = ".$user_b_id."
        AND wx_order.order_state = 2 OR wx_order.order_state = 3
        order by wx_order.order_time DESC";

        $info_arr = $order->query($sql);
        $info = $info_arr;
        return $info;
    }  
    
    //根据a用户id获取等待的订单
    public function model_get_user_a_await_order($user_type, $user_id, $order_state) {
        
        $order = D('order');
        
        $sql = "SELECT order_id,order_skill_id,skill_title,skill_user,order_number,order_price,
        order_user_a_note,order_user_b_contact_way,order_user_a_default_contact_way_value,order_state,
        order_user_b_contact_way,order_user_b_contact_way_value,order_user_b_start_time,
        order_user_b_end_time,order_user_b_start_address,order_user_b_end_address
        FROM  wx_order left join wx_skill on wx_order.order_skill_id=wx_skill.skill_id
        WHERE wx_order.order_user_".$user_type."_id = ".$user_id."
        AND wx_order.order_state = ".$order_state."
        ORDER BY wx_order.order_time DESC";
        // echo $sql;exit;
        $info_arr = $order->query($sql);
        $info = $info_arr;
        return $info;
    }  
}